#include <Energia.h>
#include "hx711.h"
#include "mylib.h"


#define SCK 7
#define DT 6
//#define RCC 1                                                                                                                                                                                                                      
#define RCC 21
#define GND 22
#define RED 43


HX711 myScale(SCK, DT);
float Tare = 0;
float k = 0.00223;
float b = 109.72;
float reading; 
enum unit{
  lb, g, kg, oz
};
float tuning(float reading);
float (*func_array[4])(float) = {gToLb, gTog, gToKg, gToOz};
unit states = g;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50; 
bool lastButtonState = HIGH; 
bool isLongPress = false; // 标记是否为长按
const unsigned long longPressThreshold = 1000; // 长按时间阈值，单位为毫秒
unsigned long pressStartTime = 0; // 按键开始按下的时间
void start(bool& Init);
void LONGPUSH(void);
bool Init = false;

//初始化引脚
void setup() {
  pinMode(GND, OUTPUT);
  pinMode(RCC, OUTPUT);
  digitalWrite(RCC, HIGH);
  digitalWrite(GND, LOW);
  pinMode(PUSH2, INPUT_PULLUP);
  pinMode(PUSH1, INPUT_PULLUP);
  pinMode(RED, OUTPUT); 
  digitalWrite(RED, LOW); 
  Serial.begin(9600);

  myScale.begin();
}

void loop() {
  //先自动校队
  start(Init);
  unsigned long currentTime = millis();
  reading = myScale.HX711_Read();
  float g = tuning(reading) - Tare;
  if (digitalRead(PUSH1) == LOW)//手动校队
  {
    Tare = tuning(reading);
    digitalWrite(RED, HIGH);
  } else {
    digitalWrite(RED, LOW);
  }
  //更换单位
  int buttonState = digitalRead(PUSH2);

   // Serial.println(states);

  if (buttonState == LOW && lastButtonState == HIGH && (currentTime - lastDebounceTime) > debounceDelay) {
    // 按键从抬起（HIGH）变为按下（LOW），并且满足防抖条件
    pressStartTime = currentTime; // 记录按键开始按下的时间
    isLongPress = false; // 重置长按标志
    Serial.println("PUSH2 pressed.");
  }
  if (buttonState == HIGH && lastButtonState == LOW && (currentTime - lastDebounceTime) > debounceDelay) {
    // 按键从按下（LOW）变为抬起（HIGH），并且满足防抖条件
    unsigned long pressDuration = currentTime - pressStartTime; // 计算按键按下的持续时间
    if (pressDuration >= longPressThreshold) {
      //长按
      isLongPress = true; // 设置长按标志
      Serial.println("Button long pressed.");
      LONGPUSH();
    } else {//短按
      Serial.println("Button short pressed.");
      states = (unit)((states + 1) % 4); 
        Serial.println("PUSH2 pressed and released!");
        lastDebounceTime = currentTime; 
    }
    lastDebounceTime = currentTime; // 更新防抖时间
  }
  lastButtonState = buttonState;
  float output = func_array[states](g);
  Serial.println(output,3);
  
}


void start(bool& Init){
  if (Init == false){
    float get[10];
    float result = 0; 
    for (int i = 0; i < 10; i ++){
      get[i] = myScale.HX711_Read();
      delay(10);
//      Serial.println(get[i]);
      result += get[i]/10;
//      Serial.println(result);
    }
//    Serial.println("InitalResult:");
//    Serial.println(result);
    Serial.println("InitalTare:");
    Tare = tuning(result);
    Serial.println(Tare);
    Init = true;
  }
}

float tuning(float reading)
{
  return 0.00223*reading + 109.72 ;
}
void LONGPUSH(void)
{
  Serial.println("Entering tuning.You should put 20g,50g on it.");
  Serial.println("Put 20g on it.If finish,push PUSH2.");
  int button2 = digitalRead(PUSH2);
  while (1)
  {
    button2 = digitalRead(PUSH2);
    if (button2 == 0) break;
  }
  delay(100);
  float r1 = myScale.HX711_Read();
  Serial.println("The reading of r1 is:");
  Serial.println(r1);
  Serial.println("Put 50g on it.If finish,push PUSH2.");
  while (1)
  {
    button2 = digitalRead(PUSH2);
    if (button2 == 0) break;
  }
  delay(100);
  float r2 = myScale.HX711_Read();
  Serial.println("The reading of r2 is:");
  Serial.println(r2);
  
  k = 30/(r2 -r1);
  b = 50 - k*r2;
  Serial.println(k);
  Serial.println(b);
  
  Serial.println("Push PUSH2 and exit.");
  while (1)
  {
    button2 = digitalRead(PUSH2);
    if (button2 == 0) break;
  }
  return ;
}
